<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="AddDialogVisible=true">添加角色</el-button>
      <el-table :data="rolesList" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 权限第一层 -->
            <el-row
              class="bb"
              :class="i==0?'bt':''"
              v-for="(item1,i) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row,item3.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 权限第二层 -->
                <el-row :class="i==0?'':'bt'" v-for="(item2, i) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeTag(scope.row,item3.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 权限第三层 -->
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeTag(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editDialogVisibleRoles(scope.row.id)"
            >编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRoles(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddDialogVisible"
      width="50%"
      @close="AddDialogVisibleClose"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogVisibleClose"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%">
      <!-- 树形控件 -->
      <el-tree ref="treeRef" show-checkbox :default-expand-all="true" node-key="id" :default-checked-keys="defKeys" :data="rightsList" :props="treeProps" ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subSetRigth">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      // 控制添加/编辑角色/分配权限对话框
      AddDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible:false,
      // 添加角色数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 编辑角色
      editForm: {
      },
      // 编辑角色验证规则
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 分配权限列表树形数据
      rightsList:[],
      // 树形控件属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      // 默认勾选的节点id值
      defKeys:[],
      // 角色id
      roleId:''
    }
  },

  methods: {
    // 获取角色列表数据
    async getRoles() {
      var { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status == 200) {
        this.rolesList = res.data
      }
      // console.log(this.rolesList)
    },
    // 监听角色关闭对话框事件
    AddDialogVisibleClose() {
      this.$refs.addForm.resetFields()
    },
    // 点击确定 添加角色
    addRoles() {
      // 发请求前先预校验
      this.$refs.addForm.validate(async flag => {
        // console.log(flag)
        if (flag) {
          var { data: res } = await this.$http.post('roles', this.addForm)
          // console.log(res)
          if (res.meta.status == 201) {
            this.$message.success(res.meta.msg)
            this.getRoles()
          } else {
            this.$message.error(res.meta.msg)
          }
          this.AddDialogVisible = false
        }
      })
    },
    // 编辑角色验证规则 重置
    editDialogVisibleClose() {
      this.$refs.editForm.resetFields()
    },
    // 点击编辑渲染数据到表单中
    async editDialogVisibleRoles(id) {
      // console.log(id)
      this.editDialogVisible = true;
      var {data:res} = await this.$http.get('roles/'+id)
      // console.log(res)
      if(res.meta.status == 200) {
        this.editForm = res.data
      }
      // console.log(this.editForm)
    },
    // 编辑提交角色
    editRoles(id) {
      // 提交之前进行预校验
      this.$refs.editForm.validate(async flag => {
        if(flag) {
          console.log(this.editForm)
         var {data:res} = await this.$http.put('roles/'+this.editForm.roleId,this.editForm)
        //  console.log(res)
         if(res.meta.status == 200) {
          this.$message.success('角色修改成功')
          this.getRoles()
         } else {
          this.$message.success('角色修改失败')
         }
         this.editDialogVisible = false
        }
      })
    },
    // 删除角色
    async delRoles(id) {
      // 用户点击删除 用弹框与用户确认
      var result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)//错误用catch捕获
      // console.log(result)
      if(result == 'confirm') {
        await this.$http.delete('roles/'+ id)
        this.$message.success('角色删除成功')
      } 
      this.getRoles()
    },
    // 删除权限标签
    async removeTag(role,id) {
      // console.log(role.id)
      // console.log(id)
      var result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        console.log(result)
        if(result != 'confirm') {
          return this.$message.info('取消了删除')
        }
        const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${id}`)
        console.log(res)
        if(res.meta.status !== 200) {
          return this.$message.error('服务器错误')
        }
        this.$message.success('删除成功')
        // 不能直接用this.getRoles 因为这是更新整个页面 不是局部更新  后台返回的数据就是这个权限的数据 重新赋值 更新
        // role.children就是角色下面的权限数据
        role.children = res.data
        
    },
    // 分配权限
    async setRights(row) {
      this.roleId = row.id //点击分配授权 将角色id保存在data中  方便subSetRigth使用
      var { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status == 200) {
        this.rightsList = res.data
      }
      // console.log(this.rightsList)
      this.defKeys = [] // 为了防止权限为空的时候 因为之前的数组存了数组
      this.getDefKeys(row)
       this.setRightDialogVisible = true
    },
    // 通过递归获取三级权限的ID
    getDefKeys(row) {
      // console.log(row)
      row.children.forEach(item => {
        if(!item.children) {
          return this.defKeys.push(item.id)
        }
        this.getDefKeys(item)
      })
    },
    // 修改权限树形 setRightDialogVisible = false  getCheckedKeys  getHalfCheckedKeys
    async subSetRigth() {
      var checkedKeys = this.$refs.treeRef.getCheckedKeys()//半选中的id数组
      var halfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()//半选中的id数组
      //  console.log(checkedKeys)
      //  console.log(halfCheckedKeys)
       var keys = [...checkedKeys,...halfCheckedKeys]
      //  console.log(keys)
       console.log(this.roleId)// 从data中获取角色id
       // 请求参数：通过 `请求体` 发送给后端 rids
       const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:keys.join(',')})
       if(res.meta.status !== 200) return this.$message.error('分配权限失败')
       this.$message.success('分配权限成功')
       this.getRoles()
       this.setRightDialogVisible = false
    }

  },

  created() {
    this.getRoles()
  }
}
</script>

<style lang='css' scoped>
.el-tag {
  margin: 7px;
}
.bt {
  border-top: 1px solid #eee;
}
.bb {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
